﻿using HslCommunication.Profinet.Omron;
using IniReadWrite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VisionRoc.Core
{
    /// <summary>
    /// 与欧姆龙Fins Udp 通信
    /// </summary>
    public class OmronfinsUdp
    {

        string Path = string.Empty;
        public OmronfinsUdp(string _Path)
        {
            //判断文件路径是否存在
            if (!Directory.Exists(_Path))
            {
                Directory.CreateDirectory(_Path);
            }
            Path = _Path + "\\OmronFinsUdp.ini";
            if (File.Exists(Path))
            {
                ReadParameter();
                OpenOmronFinsUdp();
            }
            else
            {
                Global.AddLogInfoEvent(LogLevel.Info, $"未找到 与欧姆龙PLC FinsUDP 通信 参数文件");
            }
        }
        public string IP = string.Empty;

        public int Port;

        public OmronFinsUdp PLC;
        public void OpenOmronFinsUdp()
        {
            try
            {
                PLC = new OmronFinsUdp();
                PLC.IpAddress = IP;
                PLC.Port = Port;
                PLC.ReceiveTimeout = 5000;   // 接收超时，单位毫秒
                PLC.SA1 = 192;
                PLC.GCT = 2;
                PLC.SID = 0;
                PLC.ByteTransform.DataFormat = HslCommunication.Core.DataFormat.CDAB;
                PLC.ByteTransform.IsStringReverseByteWord = true;

                Global.AddLogInfoEvent(LogLevel.OK, $"与欧姆龙PLC Fins UDP 通信对象创建成功。 IP：{IP} , 端口号：{Port}");
            }
            catch
            {
                Global.AddLogInfoEvent(LogLevel.Error, $"与欧姆龙PLC Fins UDP 通信对象创建失败。 IP：{IP} , 端口号：{Port}");
            }

        }

        /// <summary>
        /// 读取欧姆龙与欧姆龙Fins Udp 通信参数
        /// </summary>
        public void ReadParameter()
        {
            IP = IniAPI.INIGetStringValue(Path, "IP", "IP", "0");
            Port = Convert.ToInt32(IniAPI.INIGetStringValue(Path, "Port", "Port", "0"));

         
        }

        /// <summary>
        /// 保存欧姆龙与欧姆龙Fins Udp 通信参数
        /// </summary>
        public void WriteParameter()
        {
            IniAPI.INIWriteValue(Path, "IP", "IP", IP);
            IniAPI.INIWriteValue(Path, "Port", "Port", Port.ToString());
        }

    }
}
